package com.topisv.tms.web.phone;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.phone.instorage.PhoneInstorageBill;
import com.topisv.tms.entity.receiptDetail.ReceiptDetail;
import com.topisv.tms.entity.stock.CusStock;
import com.topisv.tms.entity.stock.instorage.InstorageBill;
import com.topisv.tms.entity.stock.instorage.phone.InstorageUpTaskPhone;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.account.AccountService;
import com.topisv.tms.service.stock.instorage.InstorageBillService;
import com.topisv.tms.service.stock.instorageNew.InstorageBillNewService;
import com.topisv.tms.service.stock.instorageNew.InstorageScanService;
import com.topisv.tms.service.work.WorkTaskService;
import com.topisv.tms.utils.CopyPropertiesUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/phone")
public class WMSInstorageNewController {

	private static final Logger log = LoggerFactory.getLogger(WMSInstorageNewController.class);

	@Autowired
	private InstorageBillNewService instorageBillNewService;
	@Autowired
	private InstorageBillService instorageBillService;
	@Autowired
	private InstorageScanService instorageScanService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private AccountService accountService;
   @Autowired
    private WorkTaskService workTaskService;
	// ////////////////////////////////////////////////////////点收接口///////////////////////////////////////////////////////////////////////

	/**
	 * 查询点收任务列表
	 * 
	 * @param jobuuid
	 *            用户UUID
	 * @param response
	 */
	@SuppressWarnings("unchecked")
    @RequestMapping(value = "ajaxNewInsBillList")
	public void ajaxNewInsBillList(
			@RequestParam(value = "jobuuid") String jobuuid,
			@RequestParam(value = "statue") String statue,
			@RequestParam(value = "date") String date,
			HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
//			User curUser=this.accountService.findUserByJobuuid(jobuuid);
			List<InstorageBill> instorageBillList = new ArrayList<InstorageBill>();

			 Map<String, Object> param_my=new HashMap<String, Object>();
			 param_my.put("workerUuid", jobuuid);
			 param_my.put("newstatus",statue);
			 param_my.put("fromDate",date);
			 param_my.put("toDate",date);
			List<InstorageBill> myList = this.instorageBillNewService
					.findAPPInstorageBill(param_my);
			
			instorageBillList.addAll(myList);
			
			List<PhoneInstorageBill> phoneList = CopyPropertiesUtils.ListToTargetList(myList, PhoneInstorageBill.class);

			json.put("status", "1"); // 查询成功
			json.put("content", phoneList); // 任务列表

		} catch (Exception e) {

			log.error("error", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}

	/**
	 * 根据入库单号 查询入库单
	 * 
	 * @param bill_code
	 * @param jobuuid
	 * @param response
	 */
	@RequestMapping(value = "ajaxNewInsBill")
	public void ajaxNewInsBill(
			@RequestParam(value = "billCode") String billCode,
			@RequestParam(value = "jobuuid") String jobuuid,
			HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();

//			List<InstorageBill> instorageBillList = new ArrayList<InstorageBill>();
//			Map<String, Object> param = new HashMap<String, Object>();
//			param.put("billCode", bill_code);
//			List<InstorageBill> insorageBills = instorageBillService.findInstorageBill(param);
//			instorageBillList.addAll(insorageBills);
			InstorageBill instorageBill=this.instorageBillService.loadBillByCode(billCode);
			if(null==instorageBill){
				json.put("content", "-1"); // 任务列表
			}else{
				json.put("content", instorageBill.getNewstatus()==null?"0":instorageBill.getNewstatus()); // 任务列表
			}
			json.put("status", "1"); // 查询成功
			

		} catch (Exception e) {

			log.error("error", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}

	/**
	 * APP扫描收货页面
	 * 
	 * @param bill
	 * @return
	 */
	@RequestMapping(value = "ajaxNewInsUpTask")
	public void ajaxNewInsUpTask(@RequestParam(value = "billCode") String billCode,
			@RequestParam(value = "jobuuid") String jobuuid,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			log.info("手机边收边上--->入库单号"+billCode+"收货开始");
			List<InstorageUpTaskPhone> instorageUpTaskPhones=new ArrayList<InstorageUpTaskPhone>();
			InstorageBill task = this.instorageBillNewService.loadBillByCode(billCode);
			AreaGroup areagroup=areaGroupService.findByGroupCode(task.getInwarehouseCode());
			Customers customer=customersService.findByCustomerCode(task.getCustomerCode());
			List<Map<String, Object>> result = instorageScanService
					.getInstorageScanDetail(task.getId());
			//transListMap2ListBean(result,instorageUpTaskPhones);
			if(null!=result){
				for(Map<String, Object> item:result){
					InstorageUpTaskPhone instorageUpTaskPhone=new InstorageUpTaskPhone();
					transMap2Bean(item,instorageUpTaskPhone);
					instorageUpTaskPhone.setCustomer(customer);
					instorageUpTaskPhone.setWarehouse(areagroup);
					instorageUpTaskPhones.add(instorageUpTaskPhone);
				}
			}
			json.put("status", "1");
			json.put("content", instorageUpTaskPhones);
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", "服务器异常");
			log.error("error", e);

		}
		out.print(json.toString());
	}
	
	/**
	 * 检查LPN
	 * 
	 * @param bill_code
	 * @param jobuuid
	 * @param response
	 */
	@RequestMapping(value = "ajaxCheckLpn")
	public void ajaxCheckLpn(
			@RequestParam(value = "lpn") String lpn,
			@RequestParam(value = "jobuuid") String jobuuid,
			@RequestParam(value = "billCode") String billCode,
			HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			InstorageBill  task=this.instorageBillNewService.loadBillByCode(billCode);
//			User curUser=this.accountService.findUserByJobuuid(jobuuid);
//			String areagroups =StringUtils.isBlank(curUser.getAreagroups())?"blank":curUser.getAreagroups();
//			areagroups=areagroups.split(":")[0];
			
			List<Map<String, Object>> LPNcheck=instorageScanService.checkLPN(lpn,task.getInwarehouseCode());
			if(LPNcheck.size()>0){
				json.put("status","1");
			}else{
				json.put("status","0");
				json.put("content","LPN被占用或者LPN跟仓库不对应或者不存在，请检查");
			}

		} catch (Exception e) {
			log.error("error", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}

	
	/**
	 * 确认收货
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "ajaxConfirmReceive")
	public void ajaxConfirmReceive(ServletRequest request,HttpServletResponse response) {
	    String billCode=request.getParameter("billCode");
		JSONObject json = null;
		PrintWriter out = null;
		
		boolean isLockSuccess = false;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			isLockSuccess = workTaskService.lock("ajaxConfirmReceive", billCode, "-");
            if (!isLockSuccess) {
                json.put("status", "0");
                json.put("content", "当前任务已在处理中，请勿重复处理！");
                out.print(json.toString());
                return;
            }
			
            String msg="";
			//ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			String jobuuid=request.getParameter("jobuuid");
			//String billCode=request.getParameter("billCode");
			User curUser=this.accountService.findUserByJobuuid(jobuuid);
			String skus=request.getParameter("skus");
			String lpnNum=request.getParameter("lpnNum");
			//Long billId=Long.valueOf(request.getParameter("billId"));
			String errorflag=request.getParameter("errorFlag");
			//String warehouseCode=request.getParameter("warehouseCode");
			JSONArray jsonArray = JSONArray.fromObject(skus); 
			InstorageBill instorageBill = instorageBillNewService.loadBillByCode(billCode); 
			Long billId=instorageBill.getId();
			String warehouseCode=instorageBill.getInwarehouseCode();
			String tmpNewStatus="";
			log.info("手机边收边上--->确认收货");
			log.info("手机边收边上--->确认收货---skus:"+skus);
			log.info("手机边收边上--->确认收货---lpnNum:"+lpnNum);
			log.info("手机边收边上--->确认收货---billCode:"+billCode);
			log.info("手机边收边上--->确认收货---errorflag:"+errorflag);
			log.info("手机边收边上--->确认收货---billId:"+billId);
			log.info("手机边收边上--->确认收货---warehouseCode:"+warehouseCode);
			if(jsonArray.size()>0){
				//检查LPN有没有被占用
				List<Map<String, Object>> LPNcheck=instorageScanService.checkLPN(lpnNum,warehouseCode);
				if(LPNcheck.size()>0){
					for(int i = 0; i < jsonArray.size(); i++){  
						HashMap<String,Object> param=new HashMap<String,Object>();
						JSONObject object=(JSONObject) jsonArray.get(i);
						String sku=object.getString("sku");
						int num=object.getInt("num");
						String skuName=object.getString("skuname");
						if("".equals(tmpNewStatus)){
                            tmpNewStatus=instorageBill.getNewstatus();
                        }
						//统计该入库单该sku在入库收货明细单中的数量
						List<Map<String, Object>> receiptDetailList=instorageScanService.getReceiptDetailByBillCodeAndSKU(billCode,sku);
						//该入库单该sku预约入库单明细
						List<Map<String, Object>> billItemPreSKUList=instorageScanService.getBillItemPreByBillCodeAndSKU(billCode,sku);
						if(billItemPreSKUList.size()>0){
							int billItemPreSKUNum=Integer.valueOf(String.valueOf(billItemPreSKUList.get(0).get("goods_num")));
							int countNum=0;
							if(receiptDetailList.size()>0){
								 countNum=Integer.valueOf(String.valueOf(receiptDetailList.get(0).get("countNum")));
							}
							if(billItemPreSKUNum>=(num+countNum)&&num>0){
									param.put("instorageBill", instorageBill);
									param.put("num", num);
									param.put("skuName", skuName);
									param.put("lpnNum", lpnNum);
									param.put("sku", sku);
									param.put("errorflag", errorflag);
									this.instorageBillNewService.createNewReceiptDetail(param);
									instorageScanService.updateLPNStatus(String.valueOf(LPNcheck.get(0).get("id")), "1",billCode);
									//根据入库id查询预约入库明细中的sku数量等于收货明细中sku的数量的记录
									List<Map<String, Object>> result=instorageScanService.loadAllReceiptDetailSKUNo(billId);
									//该入库单所有预约入库明细的记录
									List<Map<String, Object>> billItemPreList=instorageScanService.getAllBillItemPre(billCode);
									String flag="0";
									//边拣边上架，-1代表不走边收货边上架流程 0：新建 1:部分收货未上架  2:部分收货部分上架 3:部分收货完全上架 4:完全收货未上架 5:完全收货部分上架 6:完全收货完全上架 7:已关闭 8:已取消
									if(result.size()<billItemPreList.size()){//部分收货
										if(tmpNewStatus.equals("0")){//第一次收货
											instorageBillNewService.updateInstorageBillNewStatus(billCode,"1");
											tmpNewStatus="1";//update LiBin 20161027 bug590
											instorageBillNewService.updateInstorageBillStatus(billCode);
											instorageScanService.updateInstorageBillPreStatus(instorageBill.getAboutCode());
											flag="1";
										}
										if(tmpNewStatus.equals("3")){//部分收货完全上架
											instorageBillNewService.updateInstorageBillNewStatus(billCode,"2");
											tmpNewStatus="2";
											flag="2";
										}
									}else if(result.size()==billItemPreList.size()){//完全收货
										if(tmpNewStatus.equals("0")){//第一次收货
											instorageBillNewService.updateInstorageBillNewStatus(billCode,"4");
											tmpNewStatus="4";
											instorageBillNewService.updateInstorageBillStatus(billCode);
											instorageScanService.updateInstorageBillPreStatus(instorageBill.getAboutCode());
											flag="4";
										}else if(tmpNewStatus.equals("1")){//1:部分收货未上架
											instorageBillNewService.updateInstorageBillNewStatus(billCode,"4");
											tmpNewStatus="4";
											flag="4";
										}else if(tmpNewStatus.equals("2")){//:部分收货部分上架
											instorageBillNewService.updateInstorageBillNewStatus(billCode,"5");
											tmpNewStatus="5";
											flag="5";
										}else if(tmpNewStatus.equals("3")){//3:部分收货完全上架 
											instorageBillNewService.updateInstorageBillNewStatus(billCode,"5");
											tmpNewStatus="5";
											flag="5";
										}
									}
									//收货的入库日志
									instorageBillNewService.saveInstorageLog(instorageBill.getBillCode(),curUser,lpnNum,skuName,num,flag);
									
							}else{
								msg+=sku+"超量了，该预约数量为"+billItemPreSKUNum+",已收货:"+countNum+",扫描:"+num+";";
							}
						}
					}
					json.put("status","1");
					json.put("content",msg);
	//				json.put("items", result);
				}else{
					msg="LPN被占用";
					json.put("status","0");
					json.put("content",msg);
				}
			}else{
					json.put("status","0");
					json.put("content","预约入库单明细为空");
			}
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", "服务器异常");
			log.error("error", e);
		} finally {
		    if (isLockSuccess) {
                workTaskService.releaseLock("ajaxConfirmReceive", billCode);
            }
		}
		out.print(json.toString());
	}
	
	/**
	 * 上架页面 根据LPN查询未上架信息
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "ajaxCheckAndLoadLpnData")
	public void ajaxCheckAndLoadLpnData(ServletRequest request,HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			String lpn=request.getParameter("lpn");
			String jobuuid=request.getParameter("jobuuid");
			long begin = (System.currentTimeMillis());
			User curUser=this.accountService.findUserByJobuuid(jobuuid);
			String areagroups =StringUtils.isBlank(curUser.getAreagroups())?"blank":curUser.getAreagroups();
			areagroups=areagroups.replace(":", ",");
			log.info("手机边收边上--->获取上架信息");
			log.info("手机边收边上--->获取上架信息---lpn:"+lpn);
			log.info("手机边收边上--->获取上架信息---areagroups:"+areagroups);
			List<Map<String, Object>> LPNcheck=instorageScanService.checkUpLPN(lpn,areagroups);
			if(LPNcheck.size()>0){
				List<ReceiptDetail> upReceiptDetailList=new ArrayList<ReceiptDetail>();
				
				List<ReceiptDetail> unUpReceiptDetailList=this.instorageBillNewService.getUnUpDetailByLPN(lpn);
				if(null != unUpReceiptDetailList && !unUpReceiptDetailList.isEmpty()){
				    AreaGroup areagroup=areaGroupService.findByGroupCode(unUpReceiptDetailList.get(0).getWarehouseCode());
	                Customers customer=customersService.findByCustomerCode(unUpReceiptDetailList.get(0).getCustomerCode());
	                setReceiptDetail(unUpReceiptDetailList,areagroup,customer);
				}

//				if(unUpReceiptDetailList.size()>0){
//					for (ReceiptDetail receiptDetail : unUpReceiptDetailList) {
//						if (null!=receiptDetail.getBillCode()&&!"".equals(receiptDetail.getBillCode())) {
//							List<ReceiptDetail> tmpupReceiptDetailList=this.instorageBillNewService.getUpDetailByLPN(receiptDetail.getBillCode(),lpn);
//							upReceiptDetailList.addAll(tmpupReceiptDetailList);
//						}
//					}
//				}
				//setReceiptDetail(unUpReceiptDetailList);

				json.put("status","1");
				json.put("content1",unUpReceiptDetailList);
				json.put("content2",upReceiptDetailList);
			}else{
				json.put("status","0");
				json.put("content","LPN不存在或删除状态，请检查");
			}
			log.info("ajaxCheckAndLoadLpnData"+(System.currentTimeMillis()-begin));
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", "服务器异常");
			log.error("error", e);
			
		}
		out.print(json.toString());
	}
	
	private void setReceiptDetail(List<ReceiptDetail> receiptDetails,AreaGroup areagroup,Customers customer){
		if(null!=receiptDetails){
			for(ReceiptDetail item:receiptDetails){
				item.setWarehouse(areagroup);
				item.setCustomer(customer);
			}
		}
	}
	
	/**
	 * 检查库位
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "ajaxCheckUpStorage")
	public void ajaxCheckUpStorage(ServletRequest request,HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			String upStorage=request.getParameter("upStorage");
			List<CusStock> cusStockList=this.instorageBillNewService.checkUpStorage(upStorage);
			if(cusStockList.size()>0){
				json.put("status","0");
				json.put("content","库位存在,请重新输入!");
			}else{
				json.put("status","1");
			}
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", "服务器异常");
			log.error("error", e);
		}
		out.print(json.toString());
	}
	
	/**
	 * 上架
	 * @param taskCode
	 * @param response
	 */
	@RequestMapping(value = "ajaxUpShelf")
	public void ajaxUpShelf(ServletRequest request,HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		String msg = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			String upStorage=request.getParameter("upStorage");
			String lpn=request.getParameter("lpn");
			String sku=request.getParameter("sku");
			String num=request.getParameter("num");
			String billCode=request.getParameter("billCode");
			String errorFlag=request.getParameter("errorFlag");
			String jobuuid=request.getParameter("jobuuid");
			//上架
			log.info("手机边收边上--->开始上架---lpn:"+lpn);
			log.info("手机边收边上--->开始上架---upStorage:"+upStorage);
			log.info("手机边收边上--->开始上架---sku:"+sku);
			log.info("手机边收边上--->开始上架---num:"+num);
			log.info("手机边收边上--->开始上架---billCode:"+billCode);
			
			msg = instorageBillNewService.finishUpShelf(billCode,lpn,sku,upStorage,num,errorFlag,jobuuid);
			
			//重新查询上架信息。
			
			List<ReceiptDetail> upReceiptDetailList=new ArrayList<ReceiptDetail>();
			List<ReceiptDetail> unUpReceiptDetailList=this.instorageBillNewService.getUnUpDetailByLPN(lpn);
			
			if(null != unUpReceiptDetailList && !unUpReceiptDetailList.isEmpty()){
                AreaGroup areagroup=areaGroupService.findByGroupCode(unUpReceiptDetailList.get(0).getWarehouseCode());
                Customers customer=customersService.findByCustomerCode(unUpReceiptDetailList.get(0).getCustomerCode());
                setReceiptDetail(unUpReceiptDetailList,areagroup,customer);
            }
			
			json.put("content1",unUpReceiptDetailList);
			json.put("content2",upReceiptDetailList);
			
			json.put("status", "1");
			json.put("content", msg);
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", "服务器异常");
			log.error("error", e);
		}
		out.print(json.toString());
	}

	public void transMap2Bean(Map<String, Object> map, InstorageUpTaskPhone obj) {
		if (map == null || obj == null) {
			return;
		}
		try {
			BeanUtils.populate(obj, map);
		} catch (Exception e) {
			log.error("error", e);
		}
	}
	public void transListMap2ListBean(List<Map<String, Object>> map, List<InstorageUpTaskPhone> obj) {
		if (map == null || obj == null) {
			return;
		}
		try {
			for(Map<String, Object> item:map){
				InstorageUpTaskPhone objItem = null;
				BeanUtils.populate(objItem, item);
				obj.add(objItem);
			}
		} catch (Exception e) {
			log.error("error", e);
		}
	}

}
